<template>
  <div class="content-box">
    <div class="content">

      <button class="button" id="tencent-speech-start" @touchstart="startRecording" @touchend="stopRecording"
        :class="{ recording: isRecording }" :style="btnStyle">
        {{ isRecording ? '松开结束' : '按住说话' }}

      </button>

      <span class="connecting" :style="{'background':color}" v-if="isConnecting">建立连接中...</span>
      <span class="recognizing" :style="{'background':color}" v-if="isRecording">识别中...</span>
    </div>
  </div>
</template>

<script>

// zz.25-11.04.腾讯语音/实时语音 开始和结束方法说明，（开始结束中同步调用腾讯云和浏览器接口，所有监听代码都是监听浏览器）
export default {
  name: 'TencentSpeech',
  props: {
    btnStyle: {
      type: String,
      default: ''
    },
    color: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      params: {
        signCallback: signCallback, // 鉴权函数 用户提供鉴权函数，不传则为null
        appid: 1332379978,
        secretid: 'AKIDBG9oHYbPyJRM2ThhS1NXTJ1mLi2ECylQ',
        secretkey: 'WosiL4czA7sRmtoX4NSL0RecNvHQN6aq',
        // 实时识别接口参数
        engine_model_type: '16k_zh', // 引擎
        voice_format: 1,
        // 以下为非必填参数，可跟据业务自行修改
        hotword_id: '08003a00000000000000000000000000',
        needvad: 1,
        filter_dirty: 1,
        filter_modal: 1,
        filter_punc: 1,
        convert_num_mode: 1,
        word_info: 2
      },
      isConnecting: false,
      isRecording: false,
      pressTimer: null,
      recorder: null,
      speechRecognizer: null,
      isCanSendData: false,
      isCanStop: false,
      resultText: '',
    };
  },
  mounted() {
    this.init()
    // 检查jQuery是否全局可用
    console.log('tencentSpeech')
    console.log(window.$ === window.jQuery); // 应返回 true
    // 检查SDK是否可用
    console.log(typeof SpeechRecognizer); // 应返回 "function"

  },
  methods: {
    init() {

    },
    startRecording(e) {
      e.preventDefault();
      if (this.isRecording) return;

      this.pressTimer = setTimeout(() => {
        // console.log('11', e);
        this.isConnecting = true;
        this.speechRecognizer = null;
        this.isCanSendData = false;
        // 获取录音数据
        this.recorder = new WebRecorder();
        console.log('startRecording new recorder', this.recorder)
        this.recorder.OnReceivedData = (res) => {
          // console.log(res) // res 为采集到浏览器数据
          if (this.isCanSendData) {
            // 发送数据
            this.speechRecognizer.write(res);
          }
        };
        // 录音失败时
        this.recorder.OnError = (err) => {
          console.log(err);
          this.recorder.stop();
        };
        this.recorder.start();

        if (!this.speechRecognizer) {
          this.speechRecognizer = new SpeechRecognizer(this.params);
        }

        // 开始识别
        this.speechRecognizer.OnRecognitionStart = (res) => {
          console.log('开始识别', res);
          this.isCanSendData = true;
          this.isCanStop = true;
          this.isConnecting = false
          this.isRecording = true;
        };
        // 一句话开始
        this.speechRecognizer.OnSentenceBegin = (res) => {
          console.log('一句话开始', res);
        };
        // 识别变化时
        this.speechRecognizer.OnRecognitionResultChange = (res) => {
          console.log('识别变化时', res);
          this.resultText = `${resultText}${res.result.voice_text_str}`;
          // console.log(this.resultText)
          this.$emit('tencent-speech-resultText', this.resultText)
        };
        // 一句话结束
        this.speechRecognizer.OnSentenceEnd = (res) => {
          console.log('一句话结束', res);
          this.resultText += res.result.voice_text_str;
          // console.log(this.resultText)
          this.$emit('tencent-speech-resultText', this.resultText)
        };
        // 识别结束
        this.speechRecognizer.OnRecognitionComplete = (res) => {
          console.log('识别结束', res);
          this.$emit('tencent-speech-stop', true)
          this.isCanSendData = false;
        };
        // 识别错误
        this.speechRecognizer.OnError = (res) => {
          console.log('识别失败', res);
          this.isCanSendData = false;

          this.isConnecting = false
          this.isRecording = false;
        };
        // 建立连接
        this.speechRecognizer.start();
      }, 200);
    },
    stopRecording() {
      if (!this.isRecording) {
        clearTimeout(this.pressTimer);
        return;
      }
      this.isConnecting = false
      this.isRecording = false;
      console.log(this.isRecording, this.isConnecting)
      this.recorder.stop();
      if (this.isCanStop) {
        this.speechRecognizer.stop();
      }
    }
  }
}
</script>

<style scoped>
.recognizing,
.connecting {
  color: #fff;
  margin: 0 10px;
  position:fixed;
  top:50%;
  left:calc(50% - 75px);
  width:150px;
  border-radius: 10px;
  padding:15px;
  text-align: center;
}

.content .button {
  background: #3c9cff;
  border: 0;
  color: #fff;
  text-align: center;
  border-radius: 30px;
  cursor: pointer;
  font-size: 14px;
  width: 120px;
  height: 33px;
}
</style>